//
//  TransferView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/6/19.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class TransferView: BaseView, UITableViewDataSource, UITableViewDelegate {
    var viewModel:TransferViewModel?
    var numberTextField:BaseTextField?
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var footView:UIView = {
       let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 130))
       return view
    }()
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("划转"), y: 80, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()
    lazy var useLabel: UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 11)
        return label
    }()
   
    override func setUpUI() {
        viewModel = dataSource as? TransferViewModel
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        
        tableView.tableFooterView = footView
        
        footView.addSubview(useLabel)
        useLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(15)
        }
        footView.addSubview(selectBtn)
    }
    
    
    func setModel() {
        tableView.reloadData()
        //划出 划入展示不同的资产信息

        useLabel.text = "\(kText("可用"))  " + CYCalculate.cy_intercept(number:
            (viewModel?.model.currentAmount)!, digit: (viewModel?.model.coinPrecision)!)! + " " + (viewModel?.model.coinCode)!
    }
    
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let identy = "identyCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? BaseTableViewCell
            if cell == nil {
                cell = BaseTableViewCell(style: .default, reuseIdentifier: identy)
                cell?.nameLabel.snp.remakeConstraints { (make) in
                    make.left.equalToSuperview().offset(46)
                    make.centerY.equalToSuperview()
                }
                cell?.setArrowImage()
                cell?.contentView.addSubview((cell?.iconImage)!)
                cell?.iconImage.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview().offset(15)
                    make.centerY.equalToSuperview()
                    make.width.height.equalTo(23)
                })
                cell?.line.isHidden = true
                cell?.selectionStyle = .none
            }
            cell?.nameLabel.text =  viewModel?.model.coinCode
            cell?.iconImage.sd_setImage(with: URL(string: (viewModel?.model.logoUrl)!), placeholderImage:UIImage(named: "coinIcon") )
            cell?.iconImage.layer.cornerRadius = 10
            cell?.iconImage.layer.masksToBounds = true
            return cell!
            
        }else if indexPath.section == 1 {
            let cell:WriteChangeTableViewCell = BaseCellFactory .createTableViewCellWithModel(model: BaseModel(), tableView: tableView, style: .WriteChangeTableViewCell) as!WriteChangeTableViewCell
            cell.changeBtn.setImage(UIImage(named: "transAssetexc"), for: UIControlState.normal)
            cell.breedLabel.isHidden = true
            cell.breedBtn.isHidden = false
            cell.breedBtn.addTarget(self, action: #selector(breedAction), for: UIControlEvents.touchUpInside)
            cell.contentView.addSubview(cell.titleLabel)
            cell.coinLabel.snp.updateConstraints { (make) in
                make.width.lessThanOrEqualTo(150)
            }
            cell.coinLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
            if viewModel?.sendCoin == .legalType {
                cell.coinLabel.text = kText("法币账户")
            }else if viewModel?.sendCoin == .coinType {
                cell.coinLabel.text = kText("币币账户")
            }else {
                cell.coinLabel.text = kText("杠杆账户")
            }
            
            if viewModel?.receiveCoin == .legalType {
                cell.breedBtn.nameLabel.text = kText("法币账户")
            }else if viewModel?.receiveCoin == .coinType {
                cell.breedBtn.nameLabel.text = kText("币币账户")
            }else {
                cell.breedBtn.nameLabel.text = kText( "杠杆账户")
            }

            cell.selectionStyle = .none
//            cell.changeBtn.addTarget(self, action: #selector(exchangeAction), for: UIControlEvents.touchUpInside)
            cell.breedLabel.snp.updateConstraints { (make) in
                make.width.lessThanOrEqualTo(150)
            }
            cell.coninText.isHidden = true
            cell.breedText.isHidden = true
            return cell
        }else {
            let cell:WritePasteTableViewCell = BaseCellFactory .createTableViewCellWithModel(model: BaseModel(), tableView: tableView, style: .WritePasteTableViewCell) as!WritePasteTableViewCell
            cell.qrBtn.isHidden = true
            cell.addressBtn.isHidden = true
            cell.contentView.addSubview(cell.allBtn)
            cell.selectionStyle = .none
            cell.allBtn.addTarget(self, action: #selector(allBtnAction), for: UIControlEvents.touchUpInside)
            cell.allBtn.snp.makeConstraints { (make) in
                make.right.equalToSuperview()
                make.width.equalTo(48)
                make.height.equalTo(20)
                make.centerY.equalTo(cell.sLine!)
            }
            cell.textField.placeholder = kText("输入数量")
            
            cell.textField.text = Double(viewModel!.number)! != 0 ? viewModel?.number : ""
            cell.textField.delegate = self
            numberTextField = cell.textField
            cell.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
            cell.textField.keyboardType = UIKeyboardType.decimalPad
            cell.textField.snp.updateConstraints { (make) in
                make.right.equalToSuperview().offset(-85)
            }
            cell.contentView.addSubview(cell.zlLabel)
            cell.titleLabel.isHidden = true
            cell.zlLabel.text = viewModel?.model.coinCode
            cell.zlLabel.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-57)
                make.centerY.equalTo(cell.sLine!)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.section == 0 ? 50 : 80
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 20
        }else if section == 1 {
            return 0.1
        }else {
        return 35
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 35))
        view.backgroundColor = UIColor.clear
        return view
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 0.1))
        view.backgroundColor = UIColor.clear
        return view
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            let controller = SelectCoinViewController()
            controller.dateArr = APPAssetInfo.default.coinAssetArr
            controller.legalArr = APPAssetInfo.default.legalAssetArr
            controller.leverArr = APPAssetInfo.default.leverAssetArr
            controller.sendType = viewModel?.sendCoin
            controller.receiveType = viewModel?.receiveCoin
            controller.isTransfer = true
            if viewModel?.sendCoin == .legalType {
            }else if viewModel?.sendCoin == .coinType {
            }else {
            }
            controller.selectIndex = (viewModel?.selectIndex)!
            controller.selectBlock = {(index) in
                if self.viewModel?.selectIndex == index {
                    return
                }
                self.viewModel?.selectIndex = index
                self.viewModel?.archiveDefautAsset()
                self.viewModel?.clear()
                self.setModel()
            }
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    @objc func selectBtnAction() {
        self.endEditing(true)
        if numberTextField?.text?.count == 0 {
            CYMBShow.showMessage(kText("请输入划转数量"))
            return
        }
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
      GooglePassWordManager.creatGoolPassWord(dataSource: self, style: googleStyle.googlePassWordStyle)
    }
    
    @objc func allBtnAction() {
        viewModel?.number = CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: 8)!
        numberTextField?.text = viewModel?.number
    }
    
    @objc func exchangeAction() {
        if viewModel?.receiveCoin == .legalType {
            if APPAssetInfo.default.legalAssetArr.count == 0 {
            CYMBShow.showMessage(kText("账户资产不足请先充值"))
                return
            }
        }
        if viewModel?.receiveCoin == .coinType {
            if APPAssetInfo.default.coinAssetArr.count == 0 {
                CYMBShow.showMessage(kText("账户资产不足请先充值"))
                return
            }
        }
        
        if viewModel?.receiveCoin == .leverType {
            if APPAssetInfo.default.leverAssetArr.count == 0 {
                CYMBShow.showMessage(kText("账户资产不足请先充值"))
                return
            }
        }
        
        let minuteName = viewModel?.sendCoin
        viewModel?.sendCoin = (viewModel?.receiveCoin)!
        viewModel?.receiveCoin = minuteName!
        if viewModel?.sendCoin == .legalType {
            viewModel?.selectIndex =  (viewModel?.archiveLegalAsset())!
        }else if viewModel?.sendCoin == .coinType{
            viewModel?.selectIndex =  (viewModel?.archiveCoinAsset())!
        }else {
            viewModel?.selectIndex =  (viewModel?.archiveLeverAsset())!
        }
        
        viewModel?.number = "0.00"
        viewModel?.archiveDefautAsset()
        self.setModel()
        tableView.reloadData()
    }
    
    @objc func breedAction() {
        self.endEditing(true)
        var nameArr:[String] = []
        //判断当前币种是否在法币账户中存在
        let isHave = viewModel?.archiveIsHaveInLegal()
        if viewModel?.sendCoin == .legalType {
            nameArr = [kText("币币账户"),kText("杠杆账户")]
        }else if viewModel?.sendCoin == .coinType {
            if !isHave! {
                nameArr = [kText("杠杆账户")]
            }else {
            nameArr = [kText("法币账户"),kText("杠杆账户")]
            }
        }else {
            if !isHave! {
            nameArr = [kText("币币账户")]
            }else {
              nameArr = [kText("币币账户"),kText("法币账户")]
            }
        }
        
        SelectActionManger.manager.creatSheet(style: .commonSty, titleArr: nameArr, selectStr: nil, dataSource: self)
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension TransferView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        return textField.cheakNumberFormat(digit: (viewModel?.model.coinPrecision)!, range: range, string: string, interger: 10)
    }
    
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.text?.count == 0 {
            viewModel?.number = "0"
            return
        }
        viewModel?.number = textField.text!
    }
    
}

extension TransferView : GoolPassWordDelegate {
    func googleVerificationt(passWord:String) {
        dPrint(passWord)
        viewModel?.passWord = passWord
        viewModel?.sendAsset()
    }
    
}

extension TransferView: SelectmangerDelegate {
    func selectModel(model: SheetModel) {
        if model.selectStr == kText("币币账户") {
            viewModel?.receiveCoin = .coinType
        }else if model.selectStr == kText("法币账户") {
            viewModel?.receiveCoin = .legalType
        }else {
            viewModel?.receiveCoin = .leverType
        }
       tableView.reloadData()
    }
}
